import 'package:fate_blind_box/theme/theme_color.dart';
import 'package:fate_blind_box/widget/icon_text.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

class MomentPublishUi extends StatelessWidget {
  const MomentPublishUi({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const _MomentPublishWidget();
  }
}

class _MomentPublishWidget extends StatefulWidget {
  const _MomentPublishWidget({Key? key}) : super(key: key);

  @override
  State<_MomentPublishWidget> createState() => _MomentPublishWidgetState();
}

class _MomentPublishWidgetState extends State<_MomentPublishWidget> {
  late Size _screeSize;
  late double _screenWidth;
  late double _screenHeight;
  int currentPosition = -1;

  OverlayEntry? _overlayEntry;
  void showMenu(BuildContext context, double y) {
    if (_overlayEntry != null) {
      _overlayEntry!.remove();
      _overlayEntry = null;
    }
    double sw = MediaQuery.of(context).size.width;
    _overlayEntry = OverlayEntry(builder: (context) {
      return Positioned(
        width: 134,
        height: 54,
        left: (sw - 134) / 2,
        top: y,
        child: Stack(
          children: [
            const Positioned(
              top: 0,
              left: 55,
              child: Icon(Icons.arrow_drop_up, color: Colors.white, size: 24,),
            ),
            Container(
              margin: const EdgeInsets.only(top: 12),
              width: 134,
              height: 42,
              decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: const BorderRadius.all(Radius.circular(4)),
                  boxShadow: [
                    BoxShadow(
                        color: ThemeColor.shadowColor,
                        offset: const Offset(0.0, 4.0), //阴影xy轴偏移量
                        blurRadius: 8.0, //阴影模糊程度
                        spreadRadius: 1.0 //阴影扩散程度
                    )
                  ]
              ),
              alignment: Alignment.center,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  GestureDetector(
                    onTap: () { onClick("TEXT"); },
                    child: Image.asset(
                      "images/ic_txt.png",
                      width: 22,
                      height: 22,
                    ),
                  ),
                  const SizedBox(width: 30,),
                  GestureDetector(
                    onTap: () { onClick("IMAGE_TEXT"); },
                    child: Image.asset(
                      "images/ic_tw.png",
                      width: 22,
                      height: 22,
                    ),
                  ),
                ],
              ),
            )
          ],
        ),
      );
    });
    Overlay.of(context)?.insert(_overlayEntry!);
  }
  void dismissMenu() {
    _overlayEntry?.remove();
    _overlayEntry = null;
  }

  @override
  Widget build(BuildContext context) {
    _screeSize = MediaQuery.of(context).size;
    _screenWidth = _screeSize.width;
    _screenHeight = _screeSize.height;
    return Scaffold(
      appBar: buildTitle(),
      backgroundColor: const Color(0xFFF7F7F7),
      body: Column(
        children: [
          buildCover(),
          buildContentTitle(),
          Expanded(child: buildListView())
        ],
      ),
    );
  }

  AppBar buildTitle() {
    return AppBar(
      backgroundColor: Colors.white,
      title: Text(
        "帖子",
        style: TextStyle(color: ThemeColor.textColor, fontSize: 16),
      ),
      centerTitle: true,
      elevation: 0,
      actions: [
        Container(
          alignment: Alignment.center,
          margin: const EdgeInsets.only(right: 12),
          child: GestureDetector(
            onTap: () {},
            child: Text(
              "下一步",
              style: TextStyle(
                color: ThemeColor.mainColor,
              ),
            ),
          ),
        )
      ],
    );
  }

  /// 封面
  Widget buildCover() {
    return Stack(
      children: [
        Image.network(
          "https://img0.baidu.com/it/u=1734642970,311190705&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500",
          height: _screenWidth / 375.0 * 190,
          width: _screenWidth,
          fit: BoxFit.cover,
        ),
        Positioned(
            right: 0,
            bottom: 12,
            child: GestureDetector(
              onTap: () { onClick("OPEN_ALBUM"); },
              child: Container(
                padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 6),
                decoration: const ShapeDecoration(
                    shape: RoundedRectangleBorder(
                        borderRadius:
                        BorderRadius.horizontal(left: Radius.circular(24))),
                    color: Color.fromARGB(127, 0, 0, 0)),
                child: const IconText(
                  "更换封面",
                  style: TextStyle(
                    fontSize: 12,
                    color: Colors.white,
                  ),
                  icon: Icon(
                    Icons.photo,
                    color: Colors.white,
                    size: 14,
                  ),
                ),
              ),
            ))
      ],
    );
  }

  /// 标题
  Widget buildContentTitle() {
    return Container(
      height: 52,
      color: Colors.white,
      padding: const EdgeInsets.symmetric(horizontal: 12),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        // mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Container(
            alignment: Alignment.center,
            height: 52,
            child: Text(
              "活动标题：",
              style: TextStyle(color: ThemeColor.textColor, fontSize: 14),
            ),
          ),
          Expanded(
            child: TextField(
              cursorColor: ThemeColor.mainColor,
              cursorHeight: 24,
              maxLines: 1,
              style: TextStyle(fontSize: 14, color: ThemeColor.textColor),
              decoration: InputDecoration(
                  hintText: "",
                  counterText: "",
                  border: InputBorder.none,
                  hintStyle: TextStyle(color: ThemeColor.textColorSecond),
                  focusedBorder: null,
                  enabledBorder: null),
            ),
          )
        ],
      ),
    );
  }

  /// list
  Widget buildListView() {
    return ListView.builder(
      itemCount: 5,
      shrinkWrap: true,
      itemBuilder: (context, index) {
        return index == 4 ? buildAddBtn(index) : buildListItem(index);
      },
    );
  }
  
  /// list item
  Widget buildListItem(int index) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Container(
          margin: const EdgeInsets.only(top: 20),
          width: 24,
          height: 24,
          child: GestureDetector(
            onTapUp: (e) {
              final box = context.findRenderObject() as RenderBox;
              addItem(index, box.localToGlobal(e.globalPosition).dy);
            },
            child: Image.asset(
              "images/ic_add_circle.png",
              width: 24,
              height: 24,
            ),
          )
        ),
        Container(
          margin: const EdgeInsets.only(top: 10),
          color: Colors.white,
          padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 20),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Container(
                margin: const EdgeInsets.only(right: 16),
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(5),
                  child: Image.network(
                    "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.jj20.com%2Fup%2Fallimg%2F1114%2F050221114535%2F210502114535-10-1200.jpg&refer=http%3A%2F%2Fimg.jj20.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1656780565&t=3d8e760528ab823bb4c9bbb127378fff",
                    width: 70,
                    height: 70,
                    fit: BoxFit.cover,
                  ),
                ),
              ),
              Expanded(child: Container(
                height: 70,
                padding: const EdgeInsets.only(right: 40),
                child: Text(
                  "说点什么...",
                  style: TextStyle(color: ThemeColor.textColorSecond),
                ),
              )),
              Container(
                height: 70,
                alignment: Alignment.topLeft,
                child: GestureDetector(
                  onTap: () { deleteItem(index); },
                  child: Icon(
                    Icons.clear,
                    color: ThemeColor.textColor,
                    size: 24,
                  ),
                ),
              )
            ],
          ),
        )
      ],
    );
  }
  /// 末尾添加按钮
  GlobalKey anchorKey = GlobalKey();
  Widget buildAddBtn(int index) {
    return Container(
      alignment: Alignment.center,
      padding: const EdgeInsets.symmetric(vertical: 20),
      child: GestureDetector(
        // key: anchorKey,
        onTap: () {
          print('------------------------');
          //   RenderBox renderBox = anchorKey.currentContext!.findRenderObject()! as RenderBox;
          // var offset = renderBox.localToGlobal(Offset.zero);
          // // addItem(index, );
          // print('${offset.dx}   ${offset.dy}');
        },
        child: Image.asset(
          "images/ic_add_circle.png",
          width: 24,
          height: 24,
        ),
      )
    );
  }
  /// 添加内容
  addItem(int index, double dy) {
    currentPosition = index;
    showMenu(context, dy);
  }
  /// 删除内容
  deleteItem(int index) {
    print('delete item $index');
  }
  /// 点击事件
  onClick(String widgetId) {
    switch(widgetId) {
      case 'OPEN_ALBUM':
        getAlbumImg();
        break;
      case "TEXT":
        dismissMenu();
        break;
      case "IMAGE_TEXT":
        dismissMenu();
        break;
    }
  }
  /// 打开相册
  Future getAlbumImg() async{
    final picker = ImagePicker();
    final pickerFile = await picker.pickImage(source: ImageSource.gallery);
    if (pickerFile != null) {
      print(pickerFile.path);
    }
  }
}
